﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Shell;
using Chenglin.WPMyStep.Resources;

namespace Chenglin.WPMyStep
{
    public partial class ShowStepPage : PhoneApplicationPage
    {
        /// <summary>
        /// Get or set the records to display
        /// </summary>
        internal static StepRecord Record
        {
            get;
            set;
        }

        public ShowStepPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var stepRecord = Record;
            if (stepRecord == null || stepRecord.Locations == null || stepRecord.Locations.Length == 0)
            {
                // No data to display
                MessageBox.Show(AppResources.NoRecordsInStorage, AppResources.Error, MessageBoxButton.OK);
                NavigationService.GoBack();
            }
            else
            {
                subHeaderTextBlock.Text = stepRecord.DateTime.ToString();

                // draw the locations on the map.
                MapPolyline polyline = new MapPolyline();
                polyline.StrokeColor = (Color)Application.Current.Resources["PhoneAccentColor"];
                polyline.StrokeThickness = 5;

                var loc = stepRecord.Locations[0];
                double longitude = loc.Longitude;
                double latitude = loc.Latitude;
                var c = new System.Device.Location.GeoCoordinate { Latitude = loc.Latitude, Longitude = loc.Longitude };
                polyline.Path.Add(c);

                for (int i = 1; i < stepRecord.Locations.Length; i++)
                {
                    c = new System.Device.Location.GeoCoordinate { Latitude = stepRecord.Locations[i].Latitude, Longitude = stepRecord.Locations[i].Longitude };
                    polyline.Path.Add(c);

                    longitude = (longitude + c.Longitude) / 2;
                    latitude = (latitude + c.Latitude) / 2;
                }

                mapControl.MapElements.Add(polyline);
                mapControl.Center = new System.Device.Location.GeoCoordinate(latitude, longitude);
            }
        }
    }
}